<?php
namespace app\kucun\controller;

use app\kucun\model\WxWorkUserModel;
use QiyeWork\QiyeWorkService;
use app\kucun\model\ProductModel;
use app\kucun\model\ProductStockModel;

/**
 * Class Index
 * @package app\index\controller
 */
class Product extends Base
{


    // 新增产品
    public function add(){
        $product_name = input('product_name', '', 'string');
        $catgory_id = input('catgory_id', 0, 'intval');
        $id = input('id', 0, 'intval');
        if(empty($product_name)){
            return $this->returnError('产品名称不能为空');
        }
        if(empty($catgory_id)){
            return $this->returnError('产品分类不能为空');
        }

        $data = [];

        $data['product_name'] = $product_name;
        $data['catgory_id'] = $catgory_id;

        $data['update_time'] = time();
        $data['status'] = 1;

        if($id){
            $productModel = new ProductModel();
            $res = $productModel->where('id', $id)->update($data);
            if($res){
                return $this->returnSuccess($res, '修改成功');
            }else{
                return $this->returnSuccess($res, '修改失败');
            }
        }else{
            $data['create_time'] = time();
            $productModel = new ProductModel();
            $res = $productModel->insert($data);
            if($res){
                return $this->returnSuccess($res, '新增成功');
            }else{
                return $this->returnSuccess($res, '新增失败');
            }
        }
    }

    // 获取产品列表
    public function list(){
        $productModel = new ProductModel();

        // $productModel = $productModel;

        $result = $this->_query($productModel->with(['category']), input())->like("product_name#keyword")->page(true, false);

        // $result['list']

        $product_id_list = [];
        foreach ($result['list'] as  $product) {
            $product_id_list[] = $product['id'];
        }

        // 获取店铺库存
        $shop_stock = ProductStockModel::whereIn('product_id', $product_id_list)->where(['status' => 1])->group('product_id, shop_id')->field('product_id, shop_id, count(id) stock_num')->with(['shop'])->select();


        foreach ($result['list'] as &$product) {
            if(!isset($product['shop_stock'])) $product['shop_stock'] = [];
            foreach ($shop_stock as $shop_stock_item) {
                if($product['id'] == $shop_stock_item['product_id']){
                    $product['shop_stock'][] = $shop_stock_item;
                }
            }
        }

        foreach ($result['list'] as &$product) {
            $stock_count = 0;
            foreach ($product['shop_stock'] as $shop_stock) {
                # code...
                $stock_count += $shop_stock['stock_num'];
            }
            $product['stock_count'] = $stock_count;
        }


        return $this->returnSuccess($result);
    }

}